const async = require('async');
const _ = require('lodash');
const errorTip = require('../util/errorTip');
const request = require("../util/request");
const smsClient = require('../alicloud/smsClient');
const redisClient = require('../redis/redis');

const templateMap = {
    register:{
        code:'SMS_165413926',
        params:['code']
    },
    resetPassword:{
        code:'SMS_165413926',
        params:['code']
    },
    getBackPassword:{
        code:'SMS_165413926',
        params:['code']
    },
    adminLogin:{
        code:'SMS_165413926',
        params:['code']
    },
    delivered:{
        code:'SMS_165413926',
        params:['userId','trackingNumber']
    },
    auctionSuccess:{
        code:'SMS_165413926',
        params:['dealPrice']
    },
    withdrawApplicationResult:{
        code:'SMS_165413926',
        params:['name','operation','applicationId']
    }
}

const signName = '媚蝶';

function checkData(params,data){
    for(let i=0,dp;(dp = params[i]);i++){
        if(data[dp] === undefined){
            // callback(errorTip['短信数据不匹配']);
            return false;
        }
    }
    return true;
}

const SmsModel = {

    send: function(body,callback){
        callback = callback || function(){};
        let template = templateMap[body.type];

        if(!template){
            callback(errorTip['未知短信类型'])
            return;
        }

        let data = JSON.parse(body.data);

        if(!checkData(template.params,data)){
            callback(errorTip['短信数据不匹配']);
            return;
        }

        smsClient.sendSMS({
            PhoneNumbers: body.phone,
            SignName: signName,
            TemplateCode: template.code,
            TemplateParam: body.data
        }).then(function (ret) {
            let {Code}=ret
            if (Code === 'OK') {
                //处理返回参数
                callback(null,ret);
            }else{
                callback({code:11111111,data:ret})
            }
        }, function (err) {
            callback(err)
        })
    },

    //phone,type,data
    sendSms:function(req, callback){

        let body = req.body;

        _.each(req.body,function(value,key){
			req.sanitizeBody(key).trim();
		});		

		req.checkBody({
			phone: {
				notEmpty: {
					errorMessage: errorTip['缺少手机号'].message
			    }
			},
			type: {
				notEmpty: {
					errorMessage: errorTip['缺少短信类型'].message
			    }
            },
            data: {
				notEmpty: {
					errorMessage: errorTip['缺少短信数据'].message
			    }
			},
        });
        
        req.getValidationResult().then(function(result) {
			
			if(result.isEmpty()){
				SmsModel.send(body,callback)
			}
			else{
				let err = result.array({useFirstErrorOnly: true})[0];
				callback(err);
			}

		});

        

    }
};

module.exports = SmsModel;